#!/usr/bin/env python
# coding=utf-8
import json
import os
from medical_app.dao import tencentS3_dao
from sts.sts import Sts

# 向腾讯云请求临时密钥名返回
def getSTSResult():

    # 获取数据库中固定密钥信息
    tencentS3_info = tencentS3_dao.getTencentS3()
    config = {
        "url": "https://sts.tencentcloudapi.com/",
        # 域名，非必须，默认为 sts.tencentcloudapi.com
        "domain": "sts.tencentcloudapi.com",
        # 临时密钥有效时长，单位是秒
        "duration_seconds": 1800,
        "secret_id": tencentS3_info.secret_id,
        # 固定密钥
        "secret_key": tencentS3_info.secret_key,
        # 设置网络代理
        # 'proxy': {
        #     'http': 'xx',
        #     'https': 'xx'
        # },
        # 换成你的 bucket
        "bucket": tencentS3_info.bucket,
        # 换成 bucket 所在地区
        "region": tencentS3_info.region,
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        "allow_prefix": "*",
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        "allow_actions": [
            # 简单上传
            "name/cos:PutObject",
            "name/cos:PostObject",
            # 分片上传
            "name/cos:InitiateMultipartUpload",
            "name/cos:ListMultipartUploads",
            "name/cos:ListParts",
            "name/cos:UploadPart",
            "name/cos:CompleteMultipartUpload",
            # easy download
            "name/cos:GetObject",
            "name/cos:GetObjectUrl",
        ],
    }
    # 获取返回结果json格式
    stsResult = {}
    try:
        sts = Sts(config)
        response = sts.get_credential()
        # 将 bucket和region的信息，追加到结果字典后面，前端需要用
        response.update(
            {"bucket": tencentS3_info.bucket, "region": tencentS3_info.region}
        )
        stsResult = json.dumps(dict(response), indent=4)
        # print(json.dumps(dict(response), indent=4))
        # print('get data : ' + json.dumps(dict(response), indent=4))
    except Exception as e:
        print("")
    return stsResult
